import { getProfileApi, loginApi } from '@/api/user'
import router from '@/router'
import { setToken, removeToken, getToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,

  state() {
    return {
      token: getToken(),
      // 个人信息
      profile: {}
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    async login(context, { username, password }) {
      // 调用登录接口
      const { token } = await loginApi({ username, password })
      // console.log(res)
      // 调用mutations方法修改数据
      context.commit('SET_TOKEN', token)

      Message.success('登录成功~')
      // 1.2 跳转到首页
      router.replace('/')
    },
    logout(context) {
      context.commit('REMOVE_TOKEN')
    },
    async getProfile(ctx) {
      const res = await getProfileApi()
      // console.log(res)
      ctx.commit('setProfile', res)
      return res.permissions
    }
  }
}
